/**
 * Created by 张捉妖师 on 21/10/10.
 */

/**
 * @description 两个时间相减获取天数
 * @param {string} path
 * @returns {Boolean}
 */
export function getDaysBetween(startDate, enDate) {
  const sDate = Date.parse(startDate);
  const eDate = Date.parse(enDate);
  if (sDate > eDate) {
    return 0;
  }
  if (sDate === eDate) {
    return 1;
  }
  const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
  return days;
}
/**
 * @param {string} path
 * @returns {Boolean}
 */

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}
/**
 * @description 求数组对象某个参数的和
 * @param {arr parmas}
 * @returns
 */
export function arrayOneParameterSum(arr, parmas) {
  return arr.reduce((pre, item) => pre + item[parmas], 0)
}
/**
 * @description 验证手机号
 * @param {*} poneInput
 * @returns
 */
export function isPoneAvailable(poneInput) {
  var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (!myreg.test(poneInput)) {
    return false;
  } else {
    return true;
  }
}
/**
 * @description 验证邮箱
 * @param {*} emailInput
 * @returns
 */
export function isEmailAvailable(emailInput) {
  var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
  if (!myreg.test(emailInput)) {
    return false;
  } else {
    return true;
  }
}
/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUsername(str) {
  // const valid_map = ['admin', 'editor']
  // return valid_map.indexOf(str.trim()) >= 0
  return true;
}
export function dateToFormatHM(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");

  const hh = (dt.getHours() + "").padStart(2, "0");
  const mm = (dt.getMinutes() + "").padStart(2, "0");
  // const ss = (dt.getSeconds() + "").padStart(2, "0");

  return `${y}-${m}-${d} ${hh}:${mm}`;
}
export function dateToFormat(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");
  const hh = (dt.getHours() + "").padStart(2, "0");
  const mm = (dt.getMinutes() + "").padStart(2, "0");
  const ss = (dt.getSeconds() + "").padStart(2, "0");

  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
export function dateToFormatFour(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");

  const hh = (dt.getHours() + "").padStart(2, "0");
  const mm = (dt.getMinutes() + "").padStart(2, "0");

  return `${y}-${m}-${d} ${hh}:${mm}`;
}
export function dateToFormattwo(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");
  return `${y}-${m}-${d}`;
}
export function dateToFormatname(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");
  return `${y}年-${m}月-${d}日`;
}
export function dateToFormatthree(originDate) {
  const dt = new Date(originDate);
  const y = dt.getFullYear();
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  // const d = (dt.getDate() + "").padStart(2, "0");
  return `${y}-${m}`;
}
// 判断水产养殖 不能出现病虫害
export function farmingTypeTitle() {
  let farmingTypeNo = sessionStorage.farmingTypeNo;
  console.log(farmingTypeNo)
  if (farmingTypeNo === "sc") {
    return "病害";
  } else if (farmingTypeNo === "gc") {
    return "病害";
  } else {
    return "病虫害";
  }
}

// 点击跳转对应地方
export function toLocal(loc) {
  let toElement = document.getElementById(loc)
  toElement.scrollIntoView({
    behavior: "smooth", // 平滑过渡
    block: "start" // [可选] "start"，"center"，"end"或"nearest"。默认为"center"
  })
}
// 获取一年  所有周
export function AllWeeks(year) {
  var d = new Date(year, 0, 1);
  let WeekList = []
  while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
  }
  let to = new Date(year + 1, 0, 1);
  var i = 1;
  // eslint-disable-next-line no-unmodified-loop-condition
  for (let from = d; from < to;) {
    WeekList[i - 1] = {
      startDate: year + '-' + ((from.getMonth() + 1) < 10 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + '-' + ((from.getDate()) < 10 ? ('0' + (from.getDate())) : (from.getDate())),
      endDate: '',
      name: i + "周"
    }
    from.setDate(from.getDate() + 6);
    if (from < to) {
      from.setDate(from.getDate() + 1);
      WeekList[i - 1]['endDate'] = year + '-' + ((from.getMonth() + 1) < 10 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + '-' + ((from.getDate()) < 10 ? ('0' + (from.getDate())) : (from.getDate()))
    } else {
      to.setDate(to.getDate() - 1);
      WeekList[i - 1]['endDate'] = year + '-' + ((from.getMonth() + 1) < 10 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + '-' + ((from.getDate()) < 10 ? ('0' + (from.getDate())) : (from.getDate()))
    }
    i++;
  }
  return WeekList
}
// 获取一年  所有月
export function AllMonths(year) {
  let MonthsList = []
  for (var i = 1; i < 13; i++) {
    MonthsList.push({
      startDate: year + '-' + (i < 10 ? ('0' + i) : i) + '-' + '01',
      endDate: year + '-' + (i < 10 ? ('0' + i) : i) + '-' + (new Date(year, i, 0).getDate()),
      name: i + "月"
    })
  }
  return MonthsList
}
// 获取批量年份
export function AllYears(smallYears = 1949) {
  // 获取当前时间
  var date = new Date();
  let yearsData = []
  let nowYears = date.getFullYear()
  var Years = nowYears - smallYears
  // console.log(nowYears, Years);
  var arrYear = [];
  for (var i = 0; i <= Years; i++) {
    arrYear.push(nowYears--)
  }
  arrYear.forEach(ele => {
    // 下拉框的数组
    yearsData.push({
      value: ele,
      label: ele + '年'
    })
  })
  return yearsData
}
// 循环过滤树形数组
export function filterArrForKey(arr, children = 'children') {
  let newArr = [];
  newArr = arr?.map(item => {
    if (item[children]) {
      item = {
        ...item,
        children: this.filterArrForKey(item[children], children)
      };
    }
    return item;
  });
  newArr = newArr?.filter(item => item != null);
  return newArr;
}
// 数字转中文数字
export function toChinesNum(num) {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp) => {
    let strArr = temp.toString().split("").reverse();
    let newNum = "";
    for (let i = 0; i < strArr.length; i++) {
      newNum = (i === 0 && strArr[i] === 0 ? "" : (i > 0 && strArr[i] === 0 && strArr[i - 1] === 0 ? "" : changeNum[strArr[i]] + (strArr[i] === 0 ? unit[0] : unit[i]))) + newNum;
    }
    return newNum;
  }
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = "0" + noWan;
  }
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}
/* eslint-disable valid-typeof */
/**
 * 验证电子邮箱格式
 */
function email(value) {
  return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)
}
/**
 * 验证手机格式
 */
function mobile(value) {
  return /^1([3589]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/.test(value)
}
/**
 * 验证URL格式
 */
function url(value) {
  return /^((https|http|ftp|rtsp|mms):\/\/)(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z].[a-zA-Z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+\/?)$/
    .test(value)
}
/**
 * 验证日期格式
 */
function date(value) {
  if (!value) return false
  // 判断是否数值或者字符串数值(意味着为时间戳)，转为数值，否则new Date无法识别字符串时间戳
  if (number(value)) value = +value
  return !/Invalid|NaN/.test(new Date(value).toString())
}
/**
 * 验证ISO类型的日期格式
 */
function dateISO(value) {
  return /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
}

/**
 * 验证十进制数字
 */
function number(value) {
  return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
}

/**
 * 验证字符串
 */
function string(value) {
  return typeof value === 'string'
}

/**
 * 验证整数
 */
function digits(value) {
  return /^\d+$/.test(value)
}

/**
 * 验证身份证号码
 */
function idCard(value) {
  return /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
    value
  )
}

/**
 * 是否车牌号
 */
function carNo(value) {
  // 新能源车牌
  const xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/
  // 旧车牌
  const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/
  if (value.length === 7) {
    return creg.test(value)
  } if (value.length === 8) {
    return xreg.test(value)
  }
  return false
}

/**
 * 金额,只允许2位小数
 */
function amount(value) {
  // 金额，只允许保留两位小数
  return /^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0\.\d{1,2}$/.test(value)
}

/**
 * 中文
 */
function chinese(value) {
  const reg = /^[\u4e00-\u9fa5]+$/gi
  return reg.test(value)
}

/**
 * 只能输入字母
 */
function letter(value) {
  return /^[a-zA-Z]*$/.test(value)
}

/**
 * 只能是字母或者数字
 */
function enOrNum(value) {
  // 英文或者数字
  const reg = /^[0-9a-zA-Z]*$/g
  return reg.test(value)
}

/**
 * 验证是否包含某个值
 */
function contains(value, param) {
  return value.indexOf(param) >= 0
}

/**
 * 验证一个值范围[min, max]
 */
function range(value, param) {
  return value >= param[0] && value <= param[1]
}

/**
 * 验证一个长度范围[min, max]
 */
function rangeLength(value, param) {
  return value.length >= param[0] && value.length <= param[1]
}

/**
 * 是否固定电话
 */
function landline(value) {
  const reg = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
  return reg.test(value)
}

/**
 * 判断是否为空
 */
function empty(value) {
  switch (typeof value) {
    case 'undefined':
      return true
    case 'string':
      if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0) return true
      break
    case 'boolean':
      if (!value) return true
      break
    case 'number':
      if (value === 0 || isNaN(value)) return true
      break
    case 'object':
      if (value === null || value.length === 0) return true
      for (const i in value) {
        return false
      }
      return true
  }
  return false
}

/**
 * 是否json字符串
 */
function jsonString(value) {
  if (typeof value === 'string') {
    try {
      const obj = JSON.parse(value)
      if (typeof obj === 'object' && obj) {
        return true
      }
      return false
    } catch (e) {
      return false
    }
  }
  return false
}

/**
 * 是否数组
 */
function array(value) {
  if (typeof Array.isArray === ' function') {
    return Array.isArray(value)
  }
  return Object.prototype.toString.call(value) === '[object Array]'
}

/**
 * 是否对象
 */
function object(value) {
  return Object.prototype.toString.call(value) === '[object Object]'
}

/**
 * 是否短信验证码
 */
function code(value, len = 6) {
  return new RegExp(`^\\d{${len}}$`).test(value)
}

/**
 * 是否函数方法
 * @param {Object} value
 */
function func(value) {
  return typeof value === ' function'
}

/**
 * 是否promise对象
 * @param {Object} value
 */
function promise(value) {
  return object(value) && func(value.then) && func(value.catch)
}

/** 是否图片格式
 * @param {Object} value
 */
function image(value) {
  const newValue = value.split('?')[0]
  const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i
  return IMAGE_REGEXP.test(newValue)
}

/**
 * 是否视频格式
 * @param {Object} value
 */
function video(value) {
  const VIDEO_REGEXP = /\.(mp4|mpg|mpeg|dat|asf|avi|rm|rmvb|mov|wmv|flv|mkv|m3u8)/i
  return VIDEO_REGEXP.test(value)
}

/**
 * 是否为正则对象
 * @param {Object}
 * @return {Boolean}
 */
function regExp(o) {
  return o && Object.prototype.toString.call(o) === '[object RegExp]'
}

export default {
  email,
  mobile,
  url,
  date,
  dateISO,
  number,
  digits,
  idCard,
  carNo,
  amount,
  chinese,
  letter,
  enOrNum,
  contains,
  range,
  rangeLength,
  empty,
  isEmpty: empty,
  jsonString,
  landline,
  object,
  array,
  code,
  func,
  promise,
  video,
  image,
  regExp,
  string
}
